//
//  LCYHomeContentViewController.m
//  EPA
//
//  Created by lanou3g on 16/4/23.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "LCYHomeContentViewController.h"
#import "LCYNetWorkRequestManager.h"
#import "LCYGetCommentController.h"
#import "LCYUserInfoManager.h"
#import "LCYDBManager.h"
#import "LCYLoginViewController.h"

/// 分享
#import "UMSocial.h"
#import "NSString+LCYHtml.h"

@interface LCYHomeContentViewController ()<UIWebViewDelegate,UMSocialUIDelegate>
/// UIWebView属性
@property (nonatomic,strong) UIWebView *webView;
/// 属性存储html
@property (nonatomic,strong) NSString *htmlStr;
@end

@implementation LCYHomeContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.title = self.homeListModel.title;
    
    self.webView = [[UIWebView alloc]initWithFrame:self.view.frame];
    [self.view addSubview:self.webView];
    
    [self loadData];
    
#pragma mark - 导航栏
    // 收藏
    NSString *collectionTitle = nil;
    if ([[LCYDBManager shareManager]hasCollectContentID:(NSString *)self.homeListModel.ID]) {
        collectionTitle = @"取消收藏";
    } else {
        collectionTitle = @"收藏";
    }
    UIBarButtonItem *collectionBtn = [[UIBarButtonItem alloc]initWithTitle:collectionTitle style:UIBarButtonItemStylePlain target:self action:@selector(didClockCollectionBtn:)];
    // 评论
    UIBarButtonItem *commentBtn = [[UIBarButtonItem alloc]initWithTitle:@"评论" style:UIBarButtonItemStylePlain target:self action:@selector(didClockCommentBtn:)];
    // 分享
    UIBarButtonItem *shareBtn = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(didClockShareBtn:)];
    self.navigationItem.rightBarButtonItems = @[collectionBtn,commentBtn,shareBtn];
    
}
#pragma mark - 导航栏按钮
/// 收藏
- (void)didClockCollectionBtn:(UIBarButtonItem *)sender {
    if ([LCYUserInfoManager shareManager].uid) {
        if ([sender.title isEqualToString:@"收藏"]) {
            [[LCYDBManager shareManager]collectHomeListModel:self.homeListModel html:self.htmlStr];
            [sender setTitle:@"取消收藏"];
            
        } else {
            [sender setTitle:@"收藏"];
            [[LCYDBManager shareManager] cancelCollectionArticle:(NSString *)self.homeListModel.ID];
        }
    } else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录" preferredStyle:UIAlertControllerStyleAlert];
        [alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self login];
        }]];
        [self presentViewController:alertC animated:YES completion:nil];
    }
}
/// 评论
- (void)didClockCommentBtn:(UIBarButtonItem *)sender {
    if ([LCYUserInfoManager shareManager].uid) {
        LCYGetCommentController *commentTVC = [[LCYGetCommentController alloc]init];
        commentTVC.homeListModel = self.homeListModel;
        [self.navigationController pushViewController:commentTVC animated:YES];
    } else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录" preferredStyle:UIAlertControllerStyleAlert];
        [alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self login];
        }]];
        [self presentViewController:alertC animated:YES completion:nil];
    }

}
/// 分享
- (void)didClockShareBtn:(UIBarButtonItem *)sender {
    if ([LCYUserInfoManager shareManager].uid) {
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"564913af67e58ed0d7005bb3"
                                          shareText:self.homeListModel.content
                                         shareImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.homeListModel.coverimg]]]
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToQQ,nil]
                                           delegate:self];
    } else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录" preferredStyle:UIAlertControllerStyleAlert];
        [alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self login];
        }]];
        [self presentViewController:alertC animated:YES completion:nil];
    }

}

- (void)login {
    LCYLoginViewController *loginVC = [[LCYLoginViewController alloc]init];
    UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:loginVC];
    [self presentViewController:navc animated:YES completion:nil];
}

#pragma mark - 网络请求
- (void)loadData {
    [LCYNetWorkRequestManager requestURL:[NSURL URLWithString:READCONTENT_URL] RequestMethod:LCY_POST Params:@{@"contentid":self.homeListModel.ID,@"client":@"1",@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"auth":@"Wc06FCrkoq1DCMVzGMTikDJxQ8bm3Mrm2NpT9qWjwzcWP23tBKQx1c4P0",@"version":@"3.0.2"} Result:^(NSData *data, NSURLResponse *response, NSError *error) {
//        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        if (data) {
            NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//            NSLog(@"%@",jsonDic);
            NSDictionary *dataDic = jsonDic[@"data"];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.htmlStr = dataDic[@"html"];
            [self.webView loadHTMLString:self.htmlStr baseURL:nil];
        });
        }
    }];
}


#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"加载完成");
    [webView stringByEvaluatingJavaScriptFromString:
     @"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function ResizeImages() { "
     "var myimg,oldwidth;"
     "var maxwidth=380;" //缩放系数
     "for(i=0;i <document.images.length;i++){"
     "myimg = document.images[i];"
     "if(myimg.width > maxwidth){"
     "oldwidth = myimg.width;"
     "myimg.width = maxwidth;"
     "myimg.height = myimg.height * (maxwidth/oldwidth);"
     "}"
     "}"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];
    
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
